package com.ajun.direct;

import com.ajun.common.ConnectionFactoryBuilder;
import com.ajun.common.QueueConstants;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeoutException;

/**
 * direct Routing 模式 - 生产者
 *
 * @author AJun
 * @date 2021-07-14
 */
@Slf4j
public class Producer {

    public static void main(String[] args) {
        Connection connection = null;
        Channel channel = null;
        try {
            // 创建连接 Connection
            connection = ConnectionFactoryBuilder.getConnection("生产者");
            // 获取通道 Channel
            channel = connection.createChannel();
            // 通过 Channel 创建交换机、声明队列、绑定关系、设置路由键、接受消息
            channel.exchangeDeclare(QueueConstants.DIRECT_EXCHANGE, BuiltinExchangeType.DIRECT);
            channel.queueDeclare(QueueConstants.DIRECT_QUEUE1, false, false, false, null);
            channel.queueDeclare(QueueConstants.DIRECT_QUEUE2, false, false, false, null);
            channel.queueDeclare(QueueConstants.DIRECT_QUEUE3, false, false, false, null);
            channel.queueBind(QueueConstants.DIRECT_QUEUE1, QueueConstants.DIRECT_EXCHANGE, QueueConstants.DIRECT_QUEUE1_KEY);
            channel.queueBind(QueueConstants.DIRECT_QUEUE2, QueueConstants.DIRECT_EXCHANGE, QueueConstants.DIRECT_QUEUE2_KEY);
            channel.queueBind(QueueConstants.DIRECT_QUEUE3, QueueConstants.DIRECT_EXCHANGE, QueueConstants.DIRECT_QUEUE3_KEY);
            // 创建消息
            String message = "Hello RabbitMQ! - direct";
            // 发送消息给队列
            channel.basicPublish(
                QueueConstants.DIRECT_EXCHANGE,
                QueueConstants.DIRECT_QUEUE3_KEY,
                null,
                message.getBytes(StandardCharsets.UTF_8)
            );
            log.debug("消息发送成功, message => {}", message);
        } catch (IOException | TimeoutException e) {
            e.printStackTrace();
        } finally {
            ConnectionFactoryBuilder.close(channel, connection);
        }
    }
}
